<template>
  <h4>{{ title }}</h4>
  <canvas :id="key" class="c2d" width="1000" height="500"></canvas>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";

const key = ref("c2d" + Math.floor(Math.random() * 10000));
const props = defineProps({
  title: String,
});

onMounted(() => {
  const canvas = document.querySelector(`#${key.value}`);
  // 渲染器
  const renderer = new THREE.WebGLRenderer({ canvas });

  const fov = 40; // 视野范围
  const aspect = 2; // 相机默认值 画布的宽高比
  const near = 0.1; // 近平面
  const far = 1000; // 远平面
  // 透视投影相机
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  // 设置相机 x、y、z 位置
  camera.position.set(1, 1, 1);
  // 相机指向的场景中心
  camera.lookAt(0, 0, 0);
  // 控制相机
  const controls = new OrbitControls(camera, canvas);
  controls.update();

  // 场景
  const scene = new THREE.Scene();
  scene.background = new THREE.Color("black");

  {
    // 半球光
    const skyColor = 0xb1e1ff; // 蓝色
    const groundColor = 0xffffff; // 白色
    const intensity = 1;
    const light = new THREE.HemisphereLight(skyColor, groundColor, intensity);
    scene.add(light);
  }

  {
    // 方向光
    const color = 0xffffff;
    const intensity = 1;
    const light = new THREE.DirectionalLight(color, intensity);
    light.position.set(0, 10, 0);
    light.target.position.set(-5, 0, 0);
    scene.add(light);
    scene.add(light.target);
  }

  {
    const gltfLoader = new GLTFLoader();
    gltfLoader.load("src/assets/file/bingdundun.glb", (gltf) => {
      const root = gltf.scene;
      // 遍历所有子对象
      root.traverse((child) => {
        if (child.isMesh) {
          // 内部
          if (child.name === "oldtiger001") {
            // 金属度
            child.material.metalness = 0.5;
            // 粗糙度
            child.material.roughness = 0.8;
          }
          // 半透明外壳
          if (child.name === "oldtiger002") {
            // 启用透明
            child.material.transparent = true;
            // 透明度
            child.material.opacity = 0.5;
            // 透明反射效果
            child.material.refractionRatio = 1;
            child.material.metalness = 0.2;
            child.material.roughness = 0;
          }
        }
      });
      scene.add(root);
    });
  }
  // 渲染
  function render() {
    renderer.render(scene, camera);
    requestAnimationFrame(render);
  }

  requestAnimationFrame(render);
});
</script>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
